"use server";

import { db } from "~/server/db";
import { eq, and } from "drizzle-orm";
import { diagramCache } from "~/server/db/schema";
import { sql } from "drizzle-orm";
import postgres from "postgres";
import { drizzle } from "drizzle-orm/postgres-js";
import { diagrams } from "~/server/db/schema";
import { documents } from "~/server/db/schema";

export async function getCachedDiagram(username: string, repo: string) {
  try {
    const cachedDiagram = await db.query.diagrams.findFirst({
      where: and(
        eq(diagrams.username, username.toLowerCase()),
        eq(diagrams.repo, repo.toLowerCase())
      ),
    });

    return cachedDiagram?.diagram || null;
  } catch (e) {
    console.error("Error getting cached diagram:", e);
    return null;
  }
}

export async function getCachedExplanation(username: string, repo: string) {
  try {
    const cachedDiagram = await db.query.diagrams.findFirst({
      where: and(
        eq(diagrams.username, username.toLowerCase()),
        eq(diagrams.repo, repo.toLowerCase())
      ),
    });

    return cachedDiagram?.explanation || null;
  } catch (e) {
    console.error("Error getting cached explanation:", e);
    return null;
  }
}

export async function cacheDiagramAndExplanation(
  username: string,
  repo: string,
  diagram: string,
  explanation: string,
  usedOwnKey: boolean = false
) {
  try {
    const existingDiagram = await db.query.diagrams.findFirst({
      where: and(
        eq(diagrams.username, username.toLowerCase()),
        eq(diagrams.repo, repo.toLowerCase())
      ),
    });

    const date = new Date();

    if (existingDiagram) {
      await db
        .update(diagrams)
        .set({
          diagram,
          explanation,
          lastGenerated: date,
          usedOwnKey,
        })
        .where(
          and(
            eq(diagrams.username, username.toLowerCase()),
            eq(diagrams.repo, repo.toLowerCase())
          )
        );
    } else {
      await db.insert(diagrams).values({
        username: username.toLowerCase(),
        repo: repo.toLowerCase(),
        diagram,
        explanation,
        lastGenerated: date,
        usedOwnKey,
      });
    }

    return date;
  } catch (e) {
    console.error("Error caching diagram:", e);
    return null;
  }
}

export async function getDiagramStats() {
  try {
    const stats = await db
      .select({
        totalDiagrams: sql`COUNT(*)`,
        ownKeyUsers: sql`COUNT(CASE WHEN ${diagramCache.usedOwnKey} = true THEN 1 END)`,
        freeUsers: sql`COUNT(CASE WHEN ${diagramCache.usedOwnKey} = false THEN 1 END)`,
      })
      .from(diagramCache);

    return stats[0];
  } catch (error) {
    console.error("Error getting diagram stats:", error);
    return null;
  }
}

export async function cacheDocument(
  username: string,
  repo: string,
  document: string,
  usedOwnKey: boolean = false,
  documentType: string = "overview-doc"
) {
  try {
    console.log(`[缓存] 缓存文档: 用户名=${username}, 仓库=${repo}, 类型=${documentType}, 长度=${document.length}, 使用自己的密钥=${usedOwnKey}`);
    
    const existingDocument = await db.query.documents.findFirst({
      where: and(
        eq(documents.username, username.toLowerCase()),
        eq(documents.repo, repo.toLowerCase()),
        eq(documents.documentType, documentType)
      ),
    });

    const date = new Date();

    if (existingDocument) {
      console.log(`[缓存] 更新已有文档: 用户名=${username}, 仓库=${repo}, 类型=${documentType}`);
      await db
        .update(documents)
        .set({
          document,
          lastGenerated: date,
          usedOwnKey,
        })
        .where(
          and(
            eq(documents.username, username.toLowerCase()),
            eq(documents.repo, repo.toLowerCase()),
            eq(documents.documentType, documentType)
          )
        );
    } else {
      console.log(`[缓存] 创建新文档: 用户名=${username}, 仓库=${repo}, 类型=${documentType}`);
      await db.insert(documents).values({
        username: username.toLowerCase(),
        repo: repo.toLowerCase(),
        document,
        documentType,
        lastGenerated: date,
        usedOwnKey,
      });
    }

    console.log(`[缓存] 文档缓存成功: 用户名=${username}, 仓库=${repo}, 类型=${documentType}, 日期=${date.toISOString()}`);
    return date;
  } catch (e) {
    console.error(`[缓存] 缓存文档出错: 用户名=${username}, 仓库=${repo}, 类型=${documentType}`, e);
    return null;
  }
}

export async function getCachedDocument(
  username: string,
  repo: string,
  documentType: string = "overview-doc"
) {
  try {
    console.log(`[获取缓存] 尝试获取文档: 用户名=${username}, 仓库=${repo}, 类型=${documentType}`);
    const cachedDocument = await db.query.documents.findFirst({
      where: and(
        eq(documents.username, username.toLowerCase()),
        eq(documents.repo, repo.toLowerCase()),
        eq(documents.documentType, documentType)
      ),
    });

    if (cachedDocument) {
      console.log(`[获取缓存] 找到缓存文档: 用户名=${username}, 仓库=${repo}, 类型=${documentType}, 长度=${cachedDocument.document.length}, 日期=${cachedDocument.lastGenerated.toISOString()}`);
    } else {
      console.log(`[获取缓存] 未找到缓存文档: 用户名=${username}, 仓库=${repo}, 类型=${documentType}`);
    }

    return cachedDocument?.document || null;
  } catch (e) {
    console.error(`[获取缓存] 获取缓存文档出错: 用户名=${username}, 仓库=${repo}, 类型=${documentType}`, e);
    return null;
  }
}
